package org.jfk.core.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.jfk.core.model.SqlFilter;
import org.jfk.core.utils.JsonUtil;
import org.jfk.sys.user.User;

import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;

/**
 * 所有controller继承此类
 * @author jxf
 * 2014年12月21日
 */
public class BaseController extends Controller {
	
	public final static String PAGE_SIZE = "pageSize";
	public final static String CURRENT_PAGE = "currentPage";
	
	public final static String ERR_MSG = "errMsg";
	
	public final static int DEFAULT_PAGE_SIZE = 10;
	public final static int DIALOG_PAGE_SIZE = 5;
	public final static int DEFAULT_CURRENT_PAGE = 1;
	public final static int DEFAULT_OFFSET = 0;
	
	public final static String LAST_PREFIX = "last_";
	
	public int currentPage = DEFAULT_CURRENT_PAGE;
	public int limit = DEFAULT_PAGE_SIZE;
	public String sqlSort = "";
	
	
	protected String[][] listColumns;
	protected List<Object> param = new ArrayList<Object>();
	
	public Map resultJson = null;
	
	/**
	 * 通过list的request参数limit和offset进行分页处理。
	 */
	public void addPageAttr(){
		String order = getPara("order");
		if (order == null){
			order = this.getAttr("order");
		}
		String sort = getPara("sort");
		if (sort == null){
			sort = this.getAttr("sort");
		}
		int defaultLimit = DEFAULT_PAGE_SIZE;
		if (getPara("dlgFlag") != null){
			defaultLimit = DIALOG_PAGE_SIZE;
		}
		limit = getParaToInt("limit",defaultLimit);
		int offset = getParaToInt("offset",DEFAULT_OFFSET);
		
		currentPage = offset/limit + 1;
		
		if(sort!=null&&!"".equals(sort.trim())){
			//sqlSort = sqlSort + " order by " + sort + " " + order;
			sqlSort = " order by " + sort + " " + order;
		}
	}

	/***
	 * 通过json形式的查询条件生成SqlFilter
	 * @return
	 */
	public SqlFilter genJsonFilter(){
		SqlFilter filter = new SqlFilter();
		String jsonfilter = getPara("filter");
		
		if (jsonfilter == null){
			jsonfilter = this.getAttr("filter");
		}
		
		Map mapFilter = JsonUtil.jsonToMap(jsonfilter);
		if (mapFilter != null && mapFilter.size() > 0) {
			Iterator itr = mapFilter.keySet().iterator();
			while (itr.hasNext()) {
				Object key = itr.next();
				Map qry = (Map)mapFilter.get(key);
				String op = qry.get("op").toString();

				if ("in".equals(op)){
					Object values = qry.get("value");
					String value="";
					if (values instanceof List){//数组
						List valueList = (List) values;
						//value = value + "(";
						for (int i = 0 ; i < valueList.size() ; i++){
							value = value + valueList.get(i);
							if (i != valueList.size() - 1){
								value = value + ",";
							}
						}
					}else {//以,分隔的字符串
						value = values.toString();
					}
					
					//value = value + ")";
					String attrKey = key.toString();
					String sKey = attrKey.replace("__", ".");
					
					setAttr(attrKey,value);//将查询条件回填到查询界面
					if (attrKey.startsWith("f_") || attrKey.startsWith("v_")){//忽略用于下拉框显示的辅助属性，以及v_开头的属性
						continue;
					}
					value = "(" + value +")";
					filter.add("and", sKey, op, value);
					
				}else{
					String value = qry.get("value").toString();
					String attrKey = key.toString();
					String sKey = attrKey.replace("__", ".");
					
					setAttr(attrKey,value);//将查询条件回填到查询界面
					if (attrKey.startsWith("f_") || attrKey.startsWith("v_")){//忽略用于下拉框显示的辅助属性，以及v_开头的属性
						continue;
					}
					filter.add("and", sKey, op, value);
				}				
				
			}
			filter.end();
		}
		return filter;
	}
	
	protected void setAttrs(){
		setAttrs("");
	}
	
	protected void setBackUrl(String prefix){
		String backUrl = getPara("backUrl");
		String last_ = LAST_PREFIX;
		
		if (StrKit.notBlank(backUrl)){
			Object lastLimit = this.getSessionAttr(last_+"limit");
			lastLimit = lastLimit == null ? DEFAULT_PAGE_SIZE : lastLimit;
			backUrl = backUrl+"?limit="+lastLimit;
			
			Object lastOffset = this.getSessionAttr(last_+"offset");
			lastOffset = lastOffset == null ? DEFAULT_OFFSET : lastOffset;
			backUrl = backUrl+"&offset="+lastOffset;

			if (this.getSessionAttr(last_+"sort") != null){
				backUrl = backUrl+"&sort="+this.getSessionAttr(last_+"sort");
			}
			
			if (this.getSessionAttr(last_+"order") != null){
				backUrl = backUrl+"&order="+this.getSessionAttr(last_+"order");
			}
			
			if (this.getSessionAttr(last_+"filter") != null){
				backUrl = backUrl+"&filter="+this.getSessionAttr(last_+"filter");
			}
			
			if (this.getSessionAttr(last_+"search") != null){
				backUrl = backUrl+"&search="+this.getSessionAttr(last_+"search");
			}
			
			setAttr(prefix+"backUrl", backUrl);
		}
	}
	
	protected void setAttrs(String prefix){

		setAttr(prefix+"limit", getPara("limit"));
		setAttr(prefix+"sort",getPara("sort"));
		setAttr(prefix+"order",getPara("order"));
		setAttr(prefix+"dlgFlag",getPara("dlgFlag"));
		setColField(prefix,listColumns);

		String limit = getPara("limit");
		String sort = getPara("sort");
		String order = getPara("order");
		String offset = getPara("offset");
		String filter = getPara("filter");
		String search = getPara("search");
		
		String last_ = LAST_PREFIX;
		limit = limit==null ? String.valueOf(this.DEFAULT_PAGE_SIZE) :limit;
		offset = offset==null ? String.valueOf(this.DEFAULT_OFFSET) :offset;

		if (StrKit.notBlank(limit) && StrKit.notBlank(offset)){
			sort = sort==null ? "" :sort;
			order = order==null ? "" :order;
			filter = filter==null ? "" :filter;
			search = search==null ? "" :search;
			this.setSessionAttr(last_+"limit", limit);
			this.setSessionAttr(last_+"sort", sort);
			this.setSessionAttr(last_+"order", order);
			this.setSessionAttr(last_+"offset", offset);
			this.setSessionAttr(last_+"filter", filter);
			this.setSessionAttr(last_+"search", search);
		}		
		
	}	
	


	/**
	 * 返回列表显示字段的中文名
	 * @param s
	 * @return
	 */
	protected String[] getColNameList(String[][] s){
		String[] s1 = new String[s.length];
		for (int i = 0 ;i<s.length ;i++){
			s1[i] = s[i][1];
		}		
		return s1;
	}
	
	/**
	 * 返回列表显示字段
	 * @param s
	 * @return
	 */
	protected String[] getColFieldList(String[][] s){
		String[] s1 = new String[s.length];
		for (int i = 0 ;i<s.length ;i++){
			s1[i] = s[i][0];
		}		
		return s1;
	}
	
	/**
	 * 返回列表所显示的字段及其中文名
	 * @param s
	 * @return
	 */
	protected List<Map> setColField(String attrPrefix ,String[][] s){
		
		if (s == null){
			return null;
		}
		
		List<Map> list = new ArrayList<Map>();
		List<String> s0 = new ArrayList<String>();
		List<String> s1 = new ArrayList<String>();
		for (int i = 0 ;i<s.length ;i++){
			//标识为0的不显示到jsp中
			if (s[i].length > 2 && s[i][2].equals("0")){
				continue;
			}
			s0.add(s[i][0]);
			s1.add(s[i][1]);
			Map map = new HashMap();
			map.put("field", s[i][0]);
			map.put("fieldName", s[i][1]);
			list.add(map);
		}		
		setAttr(attrPrefix+"colFieldList", s0.toArray());
		setAttr(attrPrefix+"colNameList", s1.toArray());
		setAttr(attrPrefix+"colFieldMapList", list);
		return list;
	}	
	
	/**
	 * 返回列表所显示的字段及其中文名
	 * @param s
	 * @return
	 */
	protected List<Map> setColField(String[][] s){
		return setColField("",s);
	}
	
	public User getCurrUser() throws Exception{
		User user = (User)super.getSession().getAttribute("currUser");
		if (user == null){
			setAttr("errMsg","user login invalid");
			throw new Exception("user login invalid");
		}
		return user;
	}
	
	public void returnError(String err){
		renderText("{\"suc\":\"n\",\"err\":\""+err+"\"}");
	}

	public void returnSuc(String msg){
		renderText("{\"suc\":\"y\",\"msg\":\""+msg+"\"}");
	}	
	
	public void returnObject(String key,Object obj){
		Map<String,Object> ret = new HashMap<String,Object>();
		ret.put("suc", "y");
		ret.put(key, obj);
		renderJson(ret);
	}	
	
	public Timestamp getParaToTimestamp(String name){
		Date date = this.getParaToDate(name);
		Timestamp ts = new Timestamp(date.getTime());
		return ts;
	}
	
}
